﻿// ***********************************************************************
// Assembly         : YERIL_PI_INT
// Author           : Diego Bonilla
// Created          : 03-02-2014
//
// Last Modified By : Diego Bonilla
// Last Modified On : 03-02-2014
// ***********************************************************************
// <copyright file="DetalleMeterialEstructural.aspx.cs" company="Development Solutions CR">
//     Copyright (c) Development Solutions CR. All rights reserved.
// </copyright>
// <summary></summary>
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

/// <summary>
/// The Login namespace.
/// </summary>
namespace YERIL_PI_INT.PaginasWebs.Modulos.Login
{
    /// <summary>
    /// Class DetalleMeterialEstructural.
    /// </summary>
    public partial class DetalleMeterialEstructural : System.Web.UI.Page
    {
        /// <summary>
        /// The codigo_material
        /// </summary>
        static int codigo_material= 0;
        /// <summary>
        /// The codigo_orden
        /// </summary>
        static int codigo_orden = 0;
        /// <summary>
        /// The mensaje error
        /// </summary>
        public string MensajeError = "";
        /// <summary>
        /// The update
        /// </summary>
        public string Update ="Update";
        /// <summary>
        /// The codigo_detalle
        /// </summary>
        static int codigo_detalle = 0;
        /// <summary>
        /// The seleccion
        /// </summary>
        public string seleccion = "";
        double total_col = 0;
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            txtTotalCol.Enabled = false;
            txtTotalDol.Enabled = false;
            txtCodEstructura.Visible = false;
            txtCodMaterial.Visible = false;
            txtCodOrden.Visible = false;
            txtCodSubEstructura.Visible = false;
            txtCodSubTipoEstructura.Visible = false;

            if (Session["Codigo_Orden"] != null)
            {
                codigo_orden = Convert.ToInt32(Session["Codigo_Orden"]);
          
            }

           
               
            if (!IsPostBack)
            {
                codigo_material = 0;
                CargarGrid();
                Cargar_Combos();
                Cargar_Lista_Estructura();
                txtCodOrden.Text = codigo_orden.ToString();
                txtCodEstructura.Text = lbxEstructura.SelectedValue;
                txtCodSubEstructura.Text = lbxSubEstructura.SelectedValue;
                txtCodSubTipoEstructura.Text = lbxSubTipoEstructura.SelectedValue;
            }
            //Cargar_Lista_SubEstructura();
            
        }

        /// <summary>
        /// Cargar_s the combos.
        /// </summary>
          private void Cargar_Combos()
        {
            try
            {WSGestion.WSGestion wsgest = new WSGestion.WSGestion();
             wsgest.Url = ConfigurationManager.AppSettings.Get("dirWs");
             List<WSGestion.MOD_Seccion_Estructura> ListaSeccion = wsgest.SEL_Seccion().ToList();
             this.dlSeccion.DataSource = ListaSeccion;
             this.dlSeccion.DataValueField = "SECEST_codseccion";
             this.dlSeccion.DataTextField = "SECEST_NOMBRE";
             this.dlSeccion.DataBind();

            }
            catch (Exception exc)
            {

                MensajeError = exc.ToString();
            }
            

        }

          /// <summary>
          /// Cargars the grid.
          /// </summary>
        public void CargarGrid()
        {

            DataTable dt = new DataTable();
            dt.Columns.Add("Código Material", Type.GetType("System.String"));
            dt.Columns.Add("Material", Type.GetType("System.String"));
            dt.Columns.Add("Precio Material", Type.GetType("System.String"));
            dt.Columns.Add("Precio + IVA", Type.GetType("System.String"));

            int cont = dt.Columns.Count;
            for (int i = 0; i < listaMateriales().Count; i++)
            {
                dt.Rows.Add();
                dt.Rows[dt.Rows.Count - 1]["Código Material"] = listaMateriales()[i].MAT_codmaterial;
                dt.Rows[dt.Rows.Count - 1]["Material"] = listaMateriales()[i].MAT_descripcion;
                dt.Rows[dt.Rows.Count - 1]["Precio Material"] = listaMateriales()[i].MAT_preciomat;
                dt.Rows[dt.Rows.Count - 1]["Precio + IVA"] = listaMateriales()[i].MAT_precioivimat;

            }

            gvMaterialEstructural.DataSource = dt;
            gvMaterialEstructural.DataBind();


            DataTable dt2 = new DataTable();
            dt2.Columns.Add("Código Linea", Type.GetType("System.String"));
            dt2.Columns.Add("Estructura", Type.GetType("System.String"));
            dt2.Columns.Add("SubEstructura", Type.GetType("System.String"));
            dt2.Columns.Add("SubTipo Estructura", Type.GetType("System.String"));
            dt2.Columns.Add("Material", Type.GetType("System.String"));
            dt2.Columns.Add("Cantidad", Type.GetType("System.String"));
            dt2.Columns.Add("Total Colones", Type.GetType("System.String"));

            int cont2 = dt2.Columns.Count;
            for (int i = 0; i < listaDetalleEstructural().Count; i++)
            {
                dt2.Rows.Add();
                dt2.Rows[dt2.Rows.Count - 1]["Código Linea"] = listaDetalleEstructural()[i].DETORDEST_codlinea;
                dt2.Rows[dt2.Rows.Count - 1]["Estructura"] = listaDetalleEstructural()[i].DETORDEST_estructura;
                dt2.Rows[dt2.Rows.Count - 1]["SubEstructura"] = listaDetalleEstructural()[i].DETORDEST_clabsubest;
                dt2.Rows[dt2.Rows.Count - 1]["SubTipo Estructura"] = listaDetalleEstructural()[i].DETORDEST_subtipoest;
                dt2.Rows[dt2.Rows.Count - 1]["Material"] = listaDetalleEstructural()[i].DETORDEST_material;
                dt2.Rows[dt2.Rows.Count - 1]["Cantidad"] = listaDetalleEstructural()[i].DETORDEST_cantidadmat;
                dt2.Rows[dt2.Rows.Count - 1]["Total Colones"] = listaDetalleEstructural()[i].DETORDEST_totallineamat;

            }


            gvDetalleEstructural.DataSource = dt2;
            gvDetalleEstructural.DataBind();

        }
        /// <summary>
        /// Listas the materiales.
        /// </summary>
        /// <returns>List{WSGestion.MOD_Material}.</returns>
        private List<WSGestion.MOD_Material> listaMateriales()
        {

            WSGestion.WSGestion wsgest = new WSGestion.WSGestion();
            wsgest.Url = ConfigurationManager.AppSettings.Get("dirWs");
            List<WSGestion.MOD_Material> ListaMateriales = wsgest.SEL_Grid_Material().ToList();
            return ListaMateriales;

        }



        /// <summary>
        /// Listas the detalle estructural.
        /// </summary>
        /// <returns>List{WSGestion.MOD_DetalleEstructural}.</returns>
        private List<WSGestion.MOD_DetalleEstructural> listaDetalleEstructural()
        {

            WSGestion.WSGestion wsgest = new WSGestion.WSGestion();
            wsgest.Url = ConfigurationManager.AppSettings.Get("dirWs");
            List<WSGestion.MOD_DetalleEstructural> listaDetalleEstructural = wsgest.SEL_Grid_Detalle_Estructural(codigo_orden).ToList();
            return listaDetalleEstructural;

        }

        /// <summary>
        /// Cargar_s the lista_ estructura.
        /// </summary>
        private void Cargar_Lista_Estructura()
        {
            try
            {
                WSGestion.WSGestion wsgest = new WSGestion.WSGestion();
                wsgest.Url = ConfigurationManager.AppSettings.Get("dirWs");
                List<WSGestion.MOD_Estructura> ListaEstructura = wsgest.SEL_Grid_Estructura().ToList();
                this.lbxEstructura.DataSource = ListaEstructura;
                this.lbxEstructura.DataValueField = "EST_codestructura";
                this.lbxEstructura.DataTextField = "EST_nombre";
                this.lbxEstructura.DataBind();

                               
               

            }
            catch (Exception exc)
            {

                MensajeError = exc.ToString();
            }
        }

        /// <summary>
        /// Cargar_s the lista_ sub estructura.
        /// </summary>
         private void Cargar_Lista_SubEstructura()
        {
            try
            {
                if (lbxEstructura.SelectedValue != "")
                { int codEstructura = Convert.ToInt32(lbxEstructura.SelectedValue);
                  if (codEstructura != 0)
                    {
                    
                    WSGestion.WSGestion wsgest = new WSGestion.WSGestion();
                    wsgest.Url = ConfigurationManager.AppSettings.Get("dirWs");
                    List<WSGestion.MOD_OrdenamientoEstructural> ListaSubEstructura = wsgest.SEL_Cascada_SubEstructuras(codEstructura).ToList();
                    this.lbxSubEstructura.DataSource = ListaSubEstructura;
                    this.lbxSubEstructura.DataValueField = "ORDEST_codsubestructura";
                    this.lbxSubEstructura.DataTextField = "ORDEST_subestructura";
                    this.lbxSubEstructura.DataBind();

                    }
                    else
                    {
                    MensajeError = "No se ha seleccionado una estructura";
                    }
                }
                
                

                               
               

            }
            catch (Exception exc)
            {

                MensajeError = exc.ToString();
            }
        }

         /// <summary>
         /// Cargar_s the lista_ sub tipo estructura.
         /// </summary>
         private void Cargar_Lista_SubTipoEstructura()
         {
             try
             {
                 if (lbxSubEstructura.SelectedValue == "" || lbxEstructura.SelectedValue == "")
                 {

                 }
                 else
                 {
                     int codEstructura = Convert.ToInt32(lbxEstructura.SelectedValue);
                     int codSubEstructura = Convert.ToInt32(lbxSubEstructura.SelectedValue);
                     if (codSubEstructura != 0)
                     {

                         WSGestion.WSGestion wsgest = new WSGestion.WSGestion();
                         wsgest.Url = ConfigurationManager.AppSettings.Get("dirWs");
                         List<WSGestion.MOD_OrdenamientoEstructural> ListaSubTipoEstructura = wsgest.SEL_Cascada_SubTipoEstructuras(codEstructura, codSubEstructura).ToList();
                         this.lbxSubTipoEstructura.DataSource = ListaSubTipoEstructura;
                         this.lbxSubTipoEstructura.DataValueField = "ORDEST_codsubtipoestructura";
                         this.lbxSubTipoEstructura.DataTextField = "ORDEST_subtipoestructura";
                         this.lbxSubTipoEstructura.DataBind();

                     }
                     else
                     {
                         MensajeError = "No se ha seleccionado una estructura";
                     }
                 }







             }
             catch (Exception exc)
             {

                 MensajeError = exc.ToString();
             }
         }



         /// <summary>
         /// Handles the SelectedIndexChanged event of the lbxEstructura control.
         /// </summary>
         /// <param name="sender">The source of the event.</param>
         /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
         protected void lbxEstructura_SelectedIndexChanged(object sender, EventArgs e)
         {
             Cargar_Lista_SubEstructura();
             txtCodEstructura.Text = lbxEstructura.SelectedValue;
         }

         /// <summary>
         /// Handles the SelectedIndexChanged1 event of the lbxSubEstructura control.
         /// </summary>
         /// <param name="sender">The source of the event.</param>
         /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
         protected void lbxSubEstructura_SelectedIndexChanged1(object sender, EventArgs e)
         {
             Cargar_Lista_SubTipoEstructura();
             txtCodSubEstructura.Text = lbxSubEstructura.SelectedValue;
             MensajeError = lbxSubEstructura.SelectedValue;
         }

         /// <summary>
         /// Handles the SelectedIndexChanged event of the lbxSubTipoEstructura control.
         /// </summary>
         /// <param name="sender">The source of the event.</param>
         /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
         protected void lbxSubTipoEstructura_SelectedIndexChanged(object sender, EventArgs e)
         {
             txtCodSubTipoEstructura.Text = lbxSubTipoEstructura.SelectedValue;
         }

         /// <summary>
         /// Handles the SelectedIndexChanged event of the gvMaterialEstructural control.
         /// </summary>
         /// <param name="sender">The source of the event.</param>
         /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
         protected void gvMaterialEstructural_SelectedIndexChanged(object sender, EventArgs e)
         {
             codigo_material =Convert.ToInt32( gvMaterialEstructural.SelectedRow.Cells[1].Text);
             txtMaterial.Text = gvMaterialEstructural.SelectedRow.Cells[2].Text;
             txtPrecioUnitario.Text = gvMaterialEstructural.SelectedRow.Cells[3].Text;

             
         }

         /// <summary>
         /// Handles the TextChanged event of the txtCantMat control.
         /// </summary>
         /// <param name="sender">The source of the event.</param>
         /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
         protected void txtCantMat_TextChanged(object sender, EventArgs e)
         {
            try
             {
                 total_col = Convert.ToDouble(txtCantMat.Text) * Convert.ToDouble(txtPrecioUnitario.Text);
                 txtTotalCol.Text = total_col.ToString();

                 cr.fi.bccr.indicadoreseconomicos.wsIndicadoresEconomicos wsindicador = new cr.fi.bccr.indicadoreseconomicos.wsIndicadoresEconomicos();
                 string fecha = DateTime.Now.Date.ToString("dd/MM/yyyy");
                 DataSet tipo_cambio = wsindicador.ObtenerIndicadoresEconomicos("317", fecha, fecha, "jgaona", "N");
                 DataTable tabla = tipo_cambio.Tables[0];
                 double total_dol = total_col / Convert.ToDouble(tabla.Rows[0][2]);

                 txtTotalDol.Text = total_dol.ToString();

             }
             catch (Exception)
             {

                 MensajeError = "Imposible conectar con banco central. Cálculo en dolares con 550 colones por dolar.";

                 total_col = Convert.ToDouble(txtCantMat.Text) * Convert.ToDouble(txtPrecioUnitario.Text);
                 double total_dol = total_col / 550;

                 txtTotalDol.Text = total_dol.ToString();
             }
             
         }

         /// <summary>
         /// Handles the Click event of the btnGuardar control.
         /// </summary>
         /// <param name="sender">The source of the event.</param>
         /// <param name="e">The <see cref="ImageClickEventArgs"/> instance containing the event data.</param>
         protected void btnGuardar_Click(object sender, ImageClickEventArgs e)
         {
             try
             {
                 if ((lbxEstructura.SelectedValue == "") || (lbxSubEstructura.SelectedValue == "") || (lbxSubTipoEstructura.SelectedValue == "") || (codigo_material == 0))
                 {
                     MensajeError = "No se ha seleccionado correctamente el material o el ordenamiento estructural";
                 }
                 
                 else
                 {
                     WSGestion.WSGestion wsgest = new WSGestion.WSGestion();
                     wsgest.Url = ConfigurationManager.AppSettings.Get("dirWs");
                     WSGestion.MOD_DetalleEstructural DetalleEstructural = new WSGestion.MOD_DetalleEstructural();
                     DetalleEstructural.DETORDEST_anchomat = Convert.ToDecimal(txtAncho.Text);
                     DetalleEstructural.DETORDEST_cantidadmat = Convert.ToInt32(txtCantMat.Text);
                     DetalleEstructural.DETORDEST_codclabsubest = Convert.ToInt32(lbxSubEstructura.SelectedValue);
                     DetalleEstructural.DETORDEST_codestructura = Convert.ToInt32(lbxEstructura.SelectedValue);

                     DetalleEstructural.DETORDEST_codmat = codigo_material;
                     DetalleEstructural.DETORDEST_codorden = codigo_orden;
                     DetalleEstructural.DETORDEST_codsecest = Convert.ToInt32(dlSeccion.SelectedValue);
                     DetalleEstructural.DETORDEST_codsubtipoest = Convert.ToInt32(lbxSubTipoEstructura.SelectedValue);
                     DetalleEstructural.DETORDEST_descripcion = txtDesc.Text;
                     DetalleEstructural.DETORDEST_largomat = Convert.ToDecimal(txtLargo.Text);
                     DetalleEstructural.DETORDEST_tipocambio = Convert.ToDecimal(txtTotalDol.Text);
                     DetalleEstructural.DETORDEST_totallineamat = Convert.ToDecimal(txtTotalCol.Text);
                 
                     int cant_usu = wsgest.SEL_DetalleEstructuralByOrdenamiento(DetalleEstructural.DETORDEST_codestructura, DetalleEstructural.DETORDEST_codclabsubest, DetalleEstructural.DETORDEST_codsubtipoest, DetalleEstructural.DETORDEST_codmat, codigo_orden);
                     if (cant_usu <= 0)
                     {
                         if (wsgest.CRE_DetalleOrden(DetalleEstructural))
                         {
                             CargarGrid();
                             MensajeError = "Se ha creado el detalle";
                         }
                         else
                         {
                             MensajeError = "Procedimiento Almacenado no aceptado";
                         }
                     }
                     else
                     {

                         MensajeError = "El ordenamiento estructural junto con el material ya existen. Intente de nuevo ordenamiento y material diferente.";

                     }

                 }
                 





             }
             catch (Exception exc)
             {

                 MensajeError = exc.ToString();
             }
         }

         /// <summary>
         /// Handles the Click event of the btnSalir control.
         /// </summary>
         /// <param name="sender">The source of the event.</param>
         /// <param name="e">The <see cref="ImageClickEventArgs"/> instance containing the event data.</param>
         protected void btnSalir_Click(object sender, ImageClickEventArgs e)
         {

             Session["Codigo_Orden"] = codigo_orden;
             Session["FormAccion"] = "Editar";
             Response.Redirect("OrdenTrabajo.aspx");
         }

         /// <summary>
         /// Handles the SelectedIndexChanged event of the gvDetalleEstructural control.
         /// </summary>
         /// <param name="sender">The source of the event.</param>
         /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
         protected void gvDetalleEstructural_SelectedIndexChanged(object sender, EventArgs e)
         {
             codigo_detalle = Convert.ToInt32(gvDetalleEstructural.SelectedRow.Cells[1].Text);
             seleccion = gvDetalleEstructural.SelectedRow.Cells[5].Text;
             MensajeError = "El material seleccionado es: " + seleccion;
         }

       
    }
}